#import "DiagramCell.h"

/* DiagramCell - This is a simple graphic object to be used in the
DemoDiagram view.  It owns an NXImage object which it composites into
the diagram. */

@implementation DiagramCell:Object

- setImage:(NXImage *)anImage
{
	image=anImage;
	frameRect.origin.x=frameRect.origin.y=0.0;
	[image getSize:&frameRect.size];
	NXIntegralRect(&frameRect);		//Insure no fractional dimensions
	return self;
}

- getFrame:(NXRect *)rect
{
	*rect=frameRect;
	return self;
}

/* In this method, this item has the responsibility for moving no
further than up against the edge of the view rectangle it is passed. */

- moveBy:(NXCoord)dx :(NXCoord)dy inViewRect:(NXRect *)rect
{
	float newX,newY,minX,maxX,minY,maxY;
	
	/* Here is the desired new location */
	newX = frameRect.origin.x + dx;
	newY = frameRect.origin.y + dy;
	
	/* Here are the limits within the view rect.  Yes, this could
	be calculated once in advance, perhaps in a setViewRect: method,
	or in an initInRect: method. */
	minX = rect->origin.x;
	maxX = minX + rect->size.width - frameRect.size.width;
	minY = rect->origin.y;
	maxY = minY + rect->size.height - frameRect.size.height;
	
	/* Recalculate location constrained to the view rect. */
	if(newX < minX)newX=minX;
	if(newY < minY)newY=minY;
	if(newX > maxX)newX=maxX;
	if(newY > maxY)newY=maxY;
	
	/* Finally, "move" to the new location. */
	frameRect.origin.x=newX;
	frameRect.origin.y=newY;
	return self;
}

- mouseHit:(NXPoint *)location
{
	if(NXMouseInRect(location,&frameRect,NO)) return self;
	else return nil;
}

- drawSelf
{
	[image composite:NX_SOVER toPoint:&frameRect.origin];
	return self;
}

- drawInDirtyRect:(NXRect *)dirtyRect
{
	if(NXIntersectsRect(&frameRect,dirtyRect)){
		NXPoint intersectPoint;				//origin of intersection in view coords
		NXRect intersectRect=frameRect;

		/* Get intersection of this cell's frame with the dirty rect */
		NXIntersectionRect(dirtyRect,&intersectRect);

		/* Save intersect origin in view's coordinates */
		intersectPoint.x = intersectRect.origin.x;
		intersectPoint.y = intersectRect.origin.y;

		/* Now convert intersection rect origin to cell image's coordinates */
		intersectRect.origin.x  -=  frameRect.origin.x;
		intersectRect.origin.y  -=  frameRect.origin.y;

		/* Composite from intersection in image to point in view */
		[image composite:NX_SOVER fromRect:&intersectRect toPoint:&intersectPoint];
	}
	return self;
}


@end